package com.app.bhca.demo.tjcahttpdemo.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class base64 {
    private static BASE64Encoder encoder = new BASE64Encoder();
    private static BASE64Decoder decoder = new BASE64Decoder();

    /**
     * Base64加密，采用utf8编码方式加密
     * @param source 待加密的明文
     * @return  加密后的字符串
     */
    public static String Base64Encode(String source){
        return Base64Encode("UTF-8",source);
    }

    /**
     * Base64加密
     * @param Encoding  加密采用的编码方式
     * @param source    待加密的明文
     * @return
     */
    public static String Base64Encode(String Encoding, String source ){
        String encode = "";
        try {
            byte[] sourceByte = source.getBytes(Encoding);
            encode = encoder.encode(sourceByte);
        }catch(Exception e){
            encode = source;
        }

        return encode;
    }


    /**
     * @param result
     * @return
     */
    public static String Base64Decode(String result){
        return Base64Decode("UTF-8",result);
    }

    /**
     * @param Encoding
     * @param result
     * @return
     */
    public static String Base64Decode(String Encoding,String result){
        String decode = "";

        try {
            decode = new String(decoder.decodeBuffer(result),Encoding);
        }catch (Exception e){
            decode = result;
        }
        return decode;
    }


//    final String text = "字串文字";
//    final byte[] textByte = text.getBytes("UTF-8");
//    //编码
//    final String encodedText = encoder.encode(textByte);
//    System.out.println(encodedText);
//    //解码
//    System.out.println(new String(decoder.decodeBuffer(encodedText), "UTF-8"));
//
//        final BASE64Encoder encoder = new BASE64Encoder();
//        final BASE64Decoder decoder = new BASE64Decoder();
//        final String text = "字串文字";
//        final byte[] textByte = text.getBytes("UTF-8");
//        //编码
//        final String encodedText = encoder.encode(textByte);
//    System.out.println(encodedText);
//
//    //解码
//    System.out.println(new String(decoder.decodeBuffer(encodedText), "UTF-8"));


}
